package com.atguigu.tingshu.search.thread;

import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ClassName: ExpireThread
 * Package: com.atguigu.tingshu.search.thread
 * Description:
 *
 * @Author 梅超凡
 * @Create 2025/2/7 20:43
 * @Version 1.0
 */
public class ExpireThread {

    private volatile boolean stopMark = false;

    private StringRedisTemplate redisTemplate;

    public ExpireThread(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    /**
     * 完成续期
     */
    HashMap<String, Thread> stringThreadHashMap = new HashMap<>();
    ReentrantLock reentrantLock = new ReentrantLock();

    public void expire(String lockKey, Long interval, Long ttl) {
        reentrantLock.lock();
        Thread expireThread = stringThreadHashMap.get("expire");
        if (expireThread == null) {
            try {
                expireThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // 给redis中锁key续期
                        while (!stopMark) {
                            try {
                                Thread.sleep(interval);  // 续期间隔
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                            System.out.println(Thread.currentThread().getName()+"开始续期");
                            redisTemplate.expire(lockKey, ttl, TimeUnit.SECONDS);
                        }
                    }
                });
                stringThreadHashMap.put("expire", expireThread);
                expireThread.setDaemon(true); //设置续期线程为守护线程
                expireThread.start();
                expireThread.setName("expire-lock-thread");
            } finally {
                reentrantLock.unlock();
            }
        } else {
            expireThread.run();// 其它抢到锁的线程继续执行 expireThread的run方法。
        }


    }


    /**
     * 停止
     */
    public void stop() {
        stopMark = true;
    }
}
